package it.uniroma2.tesi.bellomaria;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnection {
	
	private static Connection conn;

	public static Properties loadProperties(){
		Properties p = new Properties();
		try {
		    p.load(new FileInputStream(RssParser.pathLavoro+"/dbcinema.properties"));
		    if(p.containsKey("db.host")==false){
		    	System.out.println("il parametro db.host nel file properties è obbligatorio");
		    	System.exit(0);
		    }
		    if(p.containsKey("db.name")==false){
		    	System.out.println("il parametro db.host nel file properties è obbligatorio");
		    	System.exit(0);
		    }
		    if(p.containsKey("db.user")==false){
		    	System.out.println("il parametro db.user nel file properties è obbligatorio");
		    	System.exit(0);
		    }
		    if(p.containsKey("db.password")==false){
		    	System.out.println("il parametro db.password nel file properties è obbligatorio");
		    	System.exit(0);
		    }
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(0);
		}
		return p;
	}
	
	public static void closeConnection(){
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection(){
		if(conn==null){
			Properties p = loadProperties();
			conn = createConnection(p.getProperty("db.host"), p.getProperty("db.name"), p.getProperty("db.user"), p.getProperty("db.password"));
		}
		return conn;
	}
	
	private static Connection createConnection(String dbHost, String dbName, String user, String psw) {
		if(dbHost==null){
			System.out.println("parametro db.host obbligatorio");
			System.exit(0);
		}
		if(dbName==null){
			System.out.println("parametro db.name obbligatorio");
			System.exit(0);
		}
		if(user==null){
			System.out.println("parametro db.user obbligatorio");
			System.exit(0);
		}
		if(psw==null){
			System.out.println("parametro db.password obbligatorio");
			System.exit(0);
		}		
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://"+dbHost+"/" + dbName + "?user=" + user + "&password=" + psw);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return con;
	}

}
